<!DOCTYPE html>
<html lang="en">
<head>
    <title>添加家人</title>
    <titleType style="display: none">familyAdd</titleType>
    <%- include('../../_global/baseLibs') %>
    <script type="text/javascript" src="/static/lib/plupload/plupload.full.min.js"></script>
    <script type="text/javascript" src="/static/lib/util.js"></script>
    <script src="/static/js/jkda/crypto-js.js"></script>
    <script src="/static/js/jkda/aes.js"></script>
    <script src="/static/js/jkda/jkda-util.js"></script>
    <link rel="stylesheet" href="/quickJs/scripts/mui/css/mui.min.css">
    <script type="text/javascript" src="/quickJs/scripts/mui/js/mui.min.js"></script>
    <link rel="stylesheet" href="/quickJs/scripts/mui/mui.picker.min.css">
    <script type="text/javascript" src="/quickJs/scripts/mui/mui.picker.min.js"></script>
</head>
<body>
<section class="page-wrap page-family">
    <!-- header start -->
    <header id="header" class="header-box grey fixed"  >
        <div class="header-content">
            <div class="left-tool">
                <a class="back" href="javascript:void(0)"><i class="iconfont icon-back"></i></a>
            </div>
            <div class="title">添加家人</div>
            <div class="right-tool">
                <a class="tool-a" id="submit">完成</a>
            </div>
        </div>
    </header>
    <!-- header end -->
    <!--content start-->
    <section class="content">
        <form id="grxxForm">
        <aside class="plane-box first family-plane">
            <ul class="default-list form-list">
                <li>
                    <a id="upLoadCheck" href="javascript:void(0);">
                        <div class="item-inner">
                            <div class="item-center">
                                头像
                            </div>
                            <div class="item-right">
                                <div class="header-pic">
                                    <img id="userSrc" class="img-response" src="/static/images/family/family-header-pic.png" />
                                    <input id="userHeader" type="text" style="display: none" />
                                </div>
                            </div>
                            <div class="item-after">
                                <i class="iconfont icon-more"></i>
                            </div>
                        </div>
                    </a>
                </li>
                <li>
                    <div class="item-inner">
                        <div class="item-title">
                            姓名
                        </div>
                        <div class="item-center">
                            <input class="input-text form-control" id="name" name="xm" type="text" placeholder="请输入真实姓名(必填)" value=""
                                   quick-config="label:'姓名', validateProxy:'notNull length', length: '16'">
                        </div>
                    </div>
                </li>
                <li>
                    <div class="item-inner">
                        <div class="item-title">
                            身份证号
                        </div>
                        <div class="item-center">
                            <input class="input-text form-control" id="patientCardId" name="sfzh" type="text" placeholder="请输入真实身份证号码(必填)" value=""
                                   quick-config="label:'身份证号', validateProxy:'notNull validPatientCardId'">
                        </div>
                    </div>
                </li>
                <li>
                    <div class="item-inner">
                        <div class="item-title">
                            手机
                        </div>
                        <div class="item-center">
                            <input class="input-text form-control" id="phoneNum" name="sj" type="text" placeholder="请输入手机号码(必填)" value=""
                                   quick-config="label:'手机', validateProxy:'notNull validPhoneNum'">
                        </div>
                    </div>
                </li>
            </ul>
        </aside>

        <aside class="plane-box">
            <ul class="default-list form-list">
                <li>
                    <div class="item-inner">
                        <div class="item-title">
                            关系
                        </div>
                        <div class="item-center">
                            <input id="relationship" class="input-text form-control" type="text"  placeholder="必填" value="" readonly
                                   quick-config="label:'关系', validateProxy:'notNull'">
                            <i class="iconfont icon-more"></i>
                        </div>
                    </div>
                </li>
            </ul>
        </aside>

        <aside  class="plane-box">
            <ul class="default-list form-list">
                <li style="display: none">
                    <div class="item-inner">
                        <div class="item-title">
                            性别
                        </div>
                        <div class="item-center">
                            <input id="gender" class="input-text form-control" type="text" placeholder="必填" value="" readonly >
                            <i class="iconfont icon-more"></i>
                        </div>
                    </div>
                </li>
                <li>
                    <div class="item-inner">
                        <div class="item-title">
                            身高(cm)
                        </div>
                        <div class="item-center">
                            <input class="input-text form-control" id="height" type="text" name="sg" placeholder="选填" value="">
                            <i class="iconfont icon-more"></i>
                        </div>
                    </div>
                </li>
                <li>
                    <div class="item-inner">
                        <div class="item-title">
                            体重(kg)
                        </div>
                        <div class="item-center">
                            <input class="input-text form-control" id="weight" type="text" name="tz" placeholder="选填" value="">
                            <i class="iconfont icon-more"></i>
                        </div>
                    </div>
                </li>
                <li>
                    <div class="item-inner">
                        <div class="item-title">
                            常住地
                        </div>
                        <div class="item-center">
                            <input class="input-text form-control" id="address" type="text" name="czd" placeholder="选填" value="">
                            <i class="iconfont icon-more"></i>
                        </div>
                    </div>
                </li>
            </ul>
        </aside>

        <aside class="plane-box">
            <ul class="default-list form-list">
                <li>
                    <div class="item-inner">
                        <div class="item-title">
                            <span class="color-warring">设为默认就诊人</span>
                        </div>
                        <div class="item-after">
                           <input id="isDefault" class="input-check" type="checkbox" />
                        </div>
                    </div>
                </li>
            </ul>
        </aside>
        </form>
     <button id="titleBtn" style="width: 100%;height:40px;color: #3082FF;position: fixed;bottom: 0px;;display: none;">提交</button>
    </section>
    <!--content end-->

</section>
<script>
    var index;
    var page_familyAdd = (function($, page_familyAdd) {
        var uri_service_jrlb_save = '/api/gzd/jrlb/save';
        var uri_service_queryTx = '/api/gzd/jrlb/queryTx';
        var item = StoreCache.removeCache('family_item_update');

        page_familyAdd.submit = submit;
        page_familyAdd.init = function(){
            if(item){
                $("body").data('item', item);
                initData(item);
            }
            initView();
        }

        /*初始化数据*/
        function initData(item){
            $(".form-control").each(function(){
                var name = $(this).attr("name");
                if(!StringUtils.isEmpty(name)){
                    var value = item[name];
                    $(this).QuickField("setData", value);
                }
            });
            /*关系 性别 是否默认就诊人 特殊赋值*/
            var value = item['gxlx'];
            var dict = $.JkcsZydmUtils.getDict({
                tableName: 'kinship'
                ,keyValue: false
            })
            var str = dict[value];
            $("#relationship").val(str);
            $("#relationship").attr("text",value);
            if (str=="本人") {
                $("#relationship").prop("readonly",true);
                $("#relationship").next().css("display", "none");
            }
            value = item['xb'];
            dict = $.JkcsZydmUtils.getDict({
                tableName: 'gender'
                ,keyValue: false
            })
            var str = dict[value];
            $("#gender").val(str);
            $("#gender").attr("text",value);

            value = item['mrjzr'];
            $("#isDefault").prop("checked", value=="0"?true:false);

            var txid = item['txid'];
            if(!StringUtils.isEmpty(txid)){
                var img = $("#userSrc");
                queryTx(img, txid);
            }
        }
        function initView(){
            $("#submit").on('click', submit);
            /*默认隐藏*/
            $("#titleBtn").on('click', submit).hide();
            var item = $("body").data('item');
            if(item){
                /*修改数据 身份证号 手机不能修改*/
                $("#patientCardId").attr("readonly", "readonly");
                $("#phoneNum").attr("readonly", "readonly");
            }
            $("#grxxForm").attr("action", uri_service_jrlb_save);
            var picker = new mui.PopPicker();

            function pickerChange(id,tableName){
                // 初始化数据
                var data = $.JkcsZydmUtils.getAry({tableName:tableName,textField:"text",valueField:"value"});
                picker.setData(data);
                /*弹出选择器 并传递关闭回调函数*/
                picker.show(function (selectItems) {
                    $(id).attr("text",selectItems[0].value);
                    $(id)[0].value=selectItems[0].text;
                });
            }
            /*关系 性别点击处理 获取焦点*/
            $("#relationship").click(function(){
                if ($(this).attr("text") != "0") {
                    $.JkcsUserInfo.getUserInfoGzd({
                        callback: function(result) {
                            if (result.jmjbxxid) {
                                pickerChange("#relationship","kinship-no");
                            } else {
                                pickerChange("#relationship","kinship");
                            }
                        }
                    });

                }
            });
            $("#gender").click(function(){
                pickerChange("#gender","gender");
            });

            /*头像添加点击回调*/
            initUserImg();
            $("#userSrc").on("click", userImgClickHandler);

            /*身份证号丢失焦点回调*/
            $("#patientCardId").on("blur", validSfzhRemote);
        }
        function queryTx(img, txid){
            $.QuickRemote.AjaxJson({
                funcName: uri_service_queryTx
                ,params: {txid: txid}
                ,callback: function(result) {
                    var src = result['src'];
                    if(!StringUtils.isEmpty(src)){
                        $(img).attr("src", src);
                    }
                }
            });
        }
        /*校验身份证号 当前用户的家人身份证不能重复*/
        function validSfzhRemote(){
            // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
            var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
            if(IdentityCodeValid($("#patientCardId").val()))
            {
                getGender($("#patientCardId").val());

            }else{
                $.QuickAlert.alertFail({
                    content: '身份证号错误，请重新输入'
                })
                return false;
            }
        }
        function getGender(value){
            if (parseInt(value.substr(16, 1)) % 2 == 1) {
                $("#gender").attr("text","1")
            } else {
                $("#gender").attr("text","2")
            }
        }
        /*提交保存*/
        function submit(){
            if($(".form-control").QuickValidate()){
                var params = {};
                var item = $("body").data('item');
                /*对应文档 修改时设置*/
                if(item){
                    params['jmjbxxid'] = item['jmjbxxid'];
                    params['txid'] = item['txid']
                }
                var sfzh = $("#patientCardId").val();
                params['csrq'] = getBirthdatByIdNo(sfzh);
                /*关系*/
                params['gxlx'] = $("#relationship").attr("text");
                /*性别*/
                var xb =$("#gender").attr("text");
                if(!StringUtils.isEmpty(xb)){
                    params['xb'] = xb;
                }
                /*默认就诊人*/
                params['mrjzr'] = $("#isDefault").is(':checked')?"0":"1";
                /*图片base64*/
                var src = $("#userSrc").attr("src");
                if(src.indexOf('data:image') == 0){
                    params['src'] = src;
                }
                $.QuickRemote.AjaxFiledFormSubmit({
                    formId: "grxxForm"
                    ,callback: saveHandler
                    ,params: params
                    ,additionParams:params
                });
            }

        }
        function saveHandler(info){
            var info = StoreCache.getCache("jkcsUserInfo");
            if((info && info.sfzh=="") ||!info){
                $.JkcsUserInfo.getUserInfoGzd({refresh: true,callback:function(){
                    saveSuccess();
                }});
            }else{
                saveSuccess();
            }
            function saveSuccess(){
                /*保存成功*/
                $.QuickAlert.alertNormal("保存成功", {
                    callback: function(){
                        // 本人信息改变才会刷新个人中心
                        if ($("#relationship").attr("text") == "0") {
                            var url =$.getUrl.pageUrl("selfCenter","personal");
                            var data = {refreshUrl:url,pageUrl:url};
                            $.QuickUrlUtils.refreshJSBridge(data);
                        }
                        // 只有从家人信息跳过来的才会刷新家人列表
                        if (item) {
                            var urlInfo =$.getUrl.pageUrl("family","familyList");
                            var dataInfo = {refreshUrl:urlInfo,pageUrl:urlInfo};
                            $.QuickUrlUtils.refreshJSBridge(dataInfo);
                        }

                        $.QuickUrlUtils.reBackAndRefreshJSBridge("*");
                    }
                });
            }
        }
        return page_familyAdd;
    })(jQuery, {})


    /*验证身份证号*/
    function validPatientCardId(){
        var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
        if(reg.test($(this).val()) === false)
        {
            return '身份证输入不合法';
        }
    }
    /*验证手机号码*/
    function validPhoneNum(){
        if(!(/^1[34578]\d{9}$/.test($(this).val()))){
            return '手机号码格式不正确，请重新输入！';
        }
    }

    function setUserImg(base64_code) {
        $('#userSrc').attr('src', base64_code);
        layer.close(index);
    };

    function initUserImg(){
        /*pc端本地上传图片*/
        if(ServiceType != "mobile"){
            var uploader_avatar = new plupload.Uploader({//创建实例的构造方法
                runtimes: 'gears,html5,html4,silverlight,flash', //上传插件初始化选用那种方式的优先级顺序
                browse_button: ['userSrc'], // 上传按钮
                url: "/api/personal/img/upload.service", //远程上传地址
                flash_swf_url: '/static/lib/plupload//Moxie.swf', //flash文件地址
                silverlight_xap_url: '/static/lib/plupload//Moxie.xap', //silverlight文件地址
                filters: {
                    max_file_size: '10mb', //最大上传文件大小（格式100b, 10kb, 10mb, 1gb）
                    mime_types: [//允许文件上传类型
                        {title: "files", extensions: "jpg,png,gif,jpeg"}
                    ]
                },
                multi_selection: false, //true:ctrl多文件上传, false 单文件上传
                init: {
                    FilesAdded: function(up, files) { //文件上传前
                        //console.log(files[0].getNative());
                        var file=files[0].getNative();
                        if(!/image\/\w+/.test(file.type)){
                            alert("请确保文件为图像类型");
                            return false;
                        }
                        var reader=new FileReader();
                        reader.readAsDataURL(file);
                        /*本地加载图片成功回调*/
                        reader.onload=function(){
                            var base64_code = this.result;
                            setUserImg(base64_code);
                        }
                    }
                }
            });
            uploader_avatar.init();
        }
    }

    /*头像点击回调*/
    function userImgClickHandler(){
        if(ServiceType == "mobile"){
            index = layer.open({
                content: '请选择图片来源。'
                ,btn: ['从相册中选择', '拍照']
                ,skin: 'footer'
                ,yes: function(index){
                    //console.log('从相册中选择');
                    $.JkcsUtils.nativePermission({
                        "type": "photoLibrary",
                        "callBackMethod": "upLoadAjax",
                        "params": {
                            "maxCount": "1",
                            "maxBytes": "2097152",
                        }
                    });
                },no: function(index){
                    $.JkcsUtils.nativePermission({
                        "type": "camera",
                        "callBackMethod": "upLoadAjax",
                        "params":{
                            "maxCount": "1",
                            "maxBytes": "2097152",
                        }
                    });
                    return false;
                }
            });
        }
    }

    //获取出生日期
    function getBirthdatByIdNo(iIdNo) {
        var tmpStr = "";
        var strReturn = "";
        if (iIdNo.length == 15) {
            tmpStr = iIdNo.substring(6, 12);
            tmpStr = "19" + tmpStr;
            tmpStr = tmpStr.substring(0, 4) + "-" + tmpStr.substring(4, 6) + "-" + tmpStr.substring(6)
            return tmpStr;
        }
        else {
            tmpStr = iIdNo.substring(6, 14);
            tmpStr = tmpStr.substring(0, 4) + "-" + tmpStr.substring(4, 6) + "-" + tmpStr.substring(6)
            return tmpStr;
        }
    }
    function IdentityCodeValid(code) { 
        code = code.trim();
        var city={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江 ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北 ",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏 ",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外 "};
        var tip = "";
        var pass= true;
        var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
        if(!reg.test(code)){
            pass = false;
        }

        else if(!city[code.substr(0,2)]){
            pass = false;
        }
        else{
            //18位身份证需要验证最后一位校验位
            if(code.length == 18){
                code = code.split('');
                //∑(ai×Wi)(mod 11)
                //加权因子
                var factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
                //校验位
                var parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
                var sum = 0;
                var ai = 0;
                var wi = 0;
                for (var i = 0; i < 17; i++)
                {
                    ai = code[i];
                    wi = factor[i];
                    sum += ai * wi;
                }
                var last = parity[sum % 11];
                if(parity[sum % 11] != code[17]){
                    pass =false;
                }
            }
        }
        return pass;
    }
</script>

</body>
</html>